<?php
/**
 * 
 * Author: wxl
 * Date: 2016/4/25
 * Time: 09:44
 * intro:充电宝充电 
 */

class ChargingService extends BaseService
{
    /*
    *$chargingId,$userId,$terminalId,$value:充电模块id,用户id,终端id,充电时长(分钟)
    */
    public function charge($chargingId,$userId,$terminalId,$value,$accountId){
        $result = $this->doCharge($chargingId,$userId,$terminalId,$value);
        if($result['status'] == 'F'){
            return $result;
        }

        $res = $this->checkWebsite($result['websiteInfo']['website_id']);
        if($res['status'] == 'F'){
            return $res;
        }

        $result = array_merge($result,$res);
         //测试服上面chargingId=12是云感,正式服上面chargingId==12的是宁波职业学院,如果推上正式服记得改成12!!!!!!!
        $userAuth=$this->isAuth($userId);
        if($chargingId ==12 ||$userAuth['auth_controller']==2){
            //宁职院
            $mUsers = D('User');
            $userInfo = $mUsers->getByUserId($userId);
            if($userInfo['type']!=1 && ($result['chargingUserInfo']['overplus_time']<$value || $value==0)){
                return array('status'=>'F','message'=>'剩余时间不足');
            }
        }else{
            if($value ==0 || (isset($result['websiteInfo']['fees']) && $result['websiteInfo']['fees']==0 && $result['chargingUserInfo']['overplus_time']<$value)){
                return array('status'=>'F','message'=>'剩余时间不足');
            }
        }

        $terminalInfo = $result['terminalInfo'];
        $websiteInfo = $result['websiteInfo'];

       $return = $this->insertCode($websiteInfo,$terminalInfo,$userId,$chargingId,1,$value);
        if(!$return){
            return array('status'=>'F','message'=>'充电失败');
        }else{
            //判断是否成功返回数据
            $mScheduled = D('Base/ChargingScheduledTasks');
            $scheduledInfo = $mScheduled->getByPk($return['tasks_id'], 'fail_code,status,tasks_id');
            if($scheduledInfo['status'] == 2){//判断是否操作指令执行失败
                
                if($scheduledInfo['fail_code'] == 1002 || $scheduledInfo['fail_code'] == 1003){
                    return array('status'=>'F','message'=>'设备网络连接异常，请联系管理员');
                }else{
                     return array('status'=>'F','message'=>'充电失败， 请稍后再尝试');
                }
            }elseif($scheduledInfo['status'] == 0){//未执行完指令，进行等待
                
                for($i=0;$i<=6;$i++){
                    //检测状态，2秒一次，执行6次
                    sleep(2);
                    $return = $this->check_tasks($scheduledInfo['tasks_id']);//继续查询
                    
                    if($return == 2){
                        break;
                    }

                }
                
                if($return == 1){//充电指令未成功 
                    return array('status'=>'F','message'=>'充电失败，请稍后再尝试');
                }

                if(isset($return['status'])){
                    return $return;
                }
            }
        }
        
        $array = array(
                'charging_id' => $chargingId,
                'website_id' => $websiteInfo['website_id'],
                'user_id' => $userId,
                'status' => 0,
                'type' => 1,
                'start_time' => time(),
                'terminal_id' => $terminalInfo['terminal_id'],
                'terminal_code' => $terminalInfo['terminal_code'],
                'freezing_time' => $value,
                'create_time' => time(),
        );

        $mLog = D('Base/ChargingLog');
        $returnLog = $mLog->update($array);//更新充电记录表


        if($returnLog !== false){
	        if($this->isAlipayBrower()){
		        $alipay  = M("Alipay")->where(array('account_id'=>$accountId))->field('alipay_id')->limit(1)->find();
		        $aluser  = M("AlipayUser")->where(array('user_id'=>$userId))->field('alipay_user_id')->limit(1)->find();
		        $log     = M("ChargingLog")->where(array('charging_log_id'=>$returnLog['charging_log_id']))->field('start_time,freezing_time')->limit(1)->find();
		        $stat_time = date("Y-m-d H:i:s",$log['start_time']);
		        $end_time  = date("Y-m-d H:i:s",($log['start_time'] + 3600 * $log['freezing_time']));
		        $message = array(
			            'head_color'=>'#85be53',
			            'url'=>C('site_url').'/base/NewCharging/index/chargingId/'.$chargingId,
			            'action_name'=>'详情',
			            'keyword1'=>array('color'=>'#000000','value'=>'您的小毛驴已经开始充电啦'),
			            'keyword2'=>array('color'=>'#000000','value'=> $stat_time),
			            'keyword3'=>array('color'=>'#000000','value'=>$log['freezing_time'].'分钟'),
			            'keyword4'=>array('color'=>'#000000','value'=>$end_time),
			            'first'   =>array('color'=>'#bebebe','value'=>date("m月d日")),
			            'remark'  =>array('color'=>'#FF0000','value'=>'小毛驴闭关修炼中，在这漫长的时间里，主人，请你自己照顾好自己吧')
		        );
		        $AlipayService = service('Alipay');
		        $AlipayService->sendMessage($alipay['alipay_id'],$aluser['alipay_user_id'],$message,"2ae8e3e6b8ec461c8562a676b92c9635");

	        }else{
		        $mWechatUser = D('Wechat/WechatUser');
		        $WechatUserInfo = $mWechatUser->getByUserId($userId);
		        if($WechatUserInfo['subscribe']){
			        $taskTime = $this->timeChangeOver($value);

			        //给用户推消息
			        import("@.Msgtpl.Base.ChargingMsgtpl");
			        $chargingMsgtpl = new ChargingMsgtpl($WechatUserInfo['wechat_id']);
			        $chargingMsgtpl->sendMessageToUser($WechatUserInfo,$chargingId,$value,$returnLog['charging_log_id']);
		        }
	        }
            return array('status'=>'S','message'=>'操作成功','id'=>$returnLog['charging_log_id']);
        }else{
            return array('status'=>'F','message'=>'操作失败');
        }

    }


    //获取电表返回值（新）
    public function check_tasks($tasks_id){
        
        $mScheduled = D('Base/ChargingScheduledTasks');
        $scheduledInfo = $mScheduled->getByPk($tasks_id , 'fail_code,status,tasks_id');//获取任务表记录
        
        if($scheduledInfo['status'] == 0){//执行指令未成功 
            return 1;
        }elseif($scheduledInfo['status'] == 2){//执行指令失败
            
            if($scheduledInfo['fail_code']==1002 || $scheduledInfo['fail_code'] == 1003){
                return array('status'=>'F','message'=>'设备网络连接异常，请联系管理员');
            }else{
                return array('status'=>'F','message'=>'充电失败，请稍后再尝试');
            }
        }else{
            return 2;
        }
    }

    //充电检测
    public function doCharge($chargingId,$userId,$terminalId){
  
        $mLog =  D('Base/ChargingLog');
        //该设备是否有人占用
        $condition = array(
                'status' => 0,
                'terminal_id' => $terminalId,
                'user_id' => array('neq', $userId),
                'type' => 1
        );

        $num = $mLog->getCount($condition);

        if($num>0){
            return array('status'=>'F','message'=>'该设备有人在使用');
        }

        $condition = array(
                'charging_id' => $chargingId,
                'status' => 0,
                'user_id' => $userId,
                'type' => 1
        );
        $chargingLogInfo = $mLog->getInfo($condition);

        if($chargingLogInfo){
            return array('status'=>'F','message'=>'您充电还没结束，请勿重复提交','url'=>U('/Base/NewCharging/charging',array('chargingId'=>$chargingId,'id'=>$chargingLogInfo['charging_log_id'])));
        }

        //充电条件判断
        $result = $this->allowCharge($chargingId,$userId,$terminalId);
        if($result['status'] == 'F'){
            return $result;
        }
        //获得充电时长配置
        $result['chargingExchange'] = $this->getChargingExchange($chargingId);

        return $result;
    }

    //充电条件判断
    public function allowCharge($chargingId,$userId,$terminalId){
        //检测终端
        $result = $this->checkTerminal($terminalId);
        if($result['status'] == 'F'){
            return $result;
        }
        $fees = $result['websiteInfo']['fees'];
   
        //检测时间
        $res = $this->checkTime($userId,$chargingId,$fees);
        if($res['status'] == 'F'){
            return $res;
        }

        return array_merge($result,$res);
    }

    //获得终端信息
    public function getTerminal($terminalId){
        $mTerminal = D('Base/ChargingTerminal');
        return $mTerminal->getByPk($terminalId, 'terminal_id,website_id,status,terminal_code,line_num,type,meter_type');
    }
    

    //获得网点信息
    public function getWebsite($websiteId){
        $mWebsite = D('Base/ChargingWebsite');
        return $mWebsite->getByPk($websiteId);
    }
 

    //判断某网点的状态
    public function checkWebsite($websiteId){
        $websiteInfo = $this->getWebsite($websiteId);
        if($websiteInfo && $websiteInfo['status'] == 1){
          return  array('status'=>'F','message'=>'该网点充电临时关闭中');
        }
        $currentTime=date('H')*3600+date('i')*60;
        
        if($websiteInfo['start_time'] > $websiteInfo['end_time']){//设置成过夜的时间限制开关
            $if = ($currentTime > $websiteInfo['start_time'] || $currentTime < $websiteInfo['end_time']);
        }else{
            $if = ($currentTime > $websiteInfo['start_time'] && $currentTime < $websiteInfo['end_time']);
        }
        
        if($websiteInfo['timeLimit'] == 1 && $if){//判断是否充电保在关闭时间段
            $currentTimeStart=date('H:i', $websiteInfo['start_time']-28800);
            $currentTimeEnd=date('H:i', $websiteInfo['end_time']-28800);
            return array('status'=>'F','message'=>"为了避免影响同学休息，{$currentTimeStart}-{$currentTimeEnd}充电功能不开放，所有充电端口均进行断电，请同学们合理安排充电时间。");
        }
        //判断是否在关闭时间内
        return array('status'=>'S','websiteInfo'=>$websiteInfo);
    }


    //判断终端信息是否存在
    public function checkTerminal($terminalId){
        $terminalInfo = $this->getTerminal($terminalId);
        if(!$terminalInfo){
            return array('status'=>'F','message'=>'参数错误');
        }

        if($terminalInfo['status'] == 1){
            return array('status'=>'F','message'=>'该终端临时关闭中'); 
        }
        $websiteInfo = $this->getWebsite($terminalInfo['website_id']);
        return array('status'=>'S','terminalInfo'=>$terminalInfo,'websiteInfo'=>$websiteInfo);
    }

    /**
     * 获得充电用户信息
     * @param $userId
     * @param $chargingId
     * @return mixed
     */
    public function getChargingUser($userId,$chargingId){
        $mUser = D('Base/ChargingUser');
        return $mUser->getInfo(array('user_id'=>$userId));
    }
    
    //判断用户信息是否正确、时间是否充足
    /*
    * fees:0：收费，1：免费
    */
    public function checkTime($userId,$chargingId,$fees = 0){

        $chargingUserInfo = $this->getChargingUser($userId,$chargingId);
        if(!$chargingUserInfo){
            return array('status'=>'F','message'=>'余额不足请充值');//帐号信息不正确
        }
        $userAuth=$this->isAuth($userId);
        if($userAuth['auth_controller']==2){
            $remainTime = $this->timeChangeOver($chargingUserInfo['overplus_time']);
            return array('status'=>'S','chargingUserInfo'=>$chargingUserInfo,'remainTime'=>$remainTime);
        }
        if(/*$chargingId!=12 &&*/ $chargingUserInfo['overplus_time'] ==0 && $fees==0){
            return array('status'=>'F','url'=>'/index.php?g=Base&m=ReCharging&a=ChargingRecharge&chargingId='.$chargingId,'message'=>'剩余时间不足，请充值','type'=>'charge');
        }
            $remainTime = $this->timeChangeOver($chargingUserInfo['overplus_time']);
            return array('status'=>'S','chargingUserInfo'=>$chargingUserInfo,'remainTime'=>$remainTime);
    }
    

    //获得充电时长配置
    public function getChargingExchange($chargingId){
        $chargingExchange = D('Base/ChargingExchange');
        $condition = array(
                'charging_id'=>$chargingId
            );
        return $chargingExchange->getList($condition,'*','value asc');
    }

    /**
     * 时间转换
     * @param int $time
     */
    public function timeChangeOver($time){
        $hour = (int) ($time / 60);
        $minute = $time % 60;
        if($hour){
            $timeChange = $hour.'小时';
        }
        if($minute){
            $timeChange .= $minute.'分钟';
        }
        return $timeChange?$timeChange:0;
    }

    /*
    * @param:$type 1:合闸  2拉闸,3.检测电流
    */
    function checkMeterType($value,$terminalInfo,$type=1){
        //电表类型判断
        if($type == 1){
            $str = 'power_supply';
        }else if($type == 2){
            $str = 'power_cuts';
        }else if($type==3){
            $str = 'power_check';
        }
        vendor('Charging.'.$terminalInfo['meter_type']);
        if(!$terminalInfo['meter_type']){//判断电表类型是否正确 
            return array('status'=>'F','message'=>'电表类型错误');
        }
        //时间获取电表合闸码
        if($terminalInfo['meter_type'] == 'Golive' && $type == 1){
            $operate_code = call_user_func(array($terminalInfo['meter_type'],$str),$terminalInfo['terminal_code'],$value);
            $supply_operate_code = 'fe '.$operate_code;
        }else{
            $operate_code = call_user_func(array($terminalInfo['meter_type'],$str),$terminalInfo['terminal_code']);//获取电表合闸码
            $supply_operate_code = 'fe '.$operate_code;
        }

        $out_success = call_user_func(array($terminalInfo['meter_type'],'cuts_success'),$terminalInfo['terminal_code']);//获取电表成功返回码
        return array('status'=>'S','operate_code'=>$operate_code,'supply_operate_code'=>$supply_operate_code,'out_success'=>$out_success);
    }



    /*
    * 结束充电
    */
    public function endCharge($chargingLogId,$chargingId,$userId){
        $chargingUserInfo = $this->getChargingUser($userId,$chargingId);
        if(!$chargingUserInfo){
            return array('status'=>'F','message'=>'用户信息不存在');
        }

        //获得充电信息
        $mLog = D('Base/ChargingLog');
        $logInfo = $mLog->getByPk($chargingLogId);
        if(!$logInfo || $logInfo['status'] == 1){
            return array('status'=>'F','message'=>'您没有充电任务，无法结束充电');
        }

       
        //获得网点、终端信息
        $websiteInfo = $this->getWebsite($logInfo['website_id']);
        $terminalInfo = $this->getTerminal($logInfo['terminal_id']);

        $endTime = time();
        $consumeTime = ceil(($endTime - $logInfo['start_time'])/60);
        if($consumeTime > $logInfo['freezing_time']){
            $consumeTime = $logInfo['freezing_time'];//如果充电时间超出冻结时长则改为冻结时长
        }


        //结束扣费
        if($value['charging_id'] == 12){
            $mUsers = D('User');
            $uInfo = $mUsers->getByUserId($value['user_id']);
            if($uInfo['type'] == 1){//宁职院 教师是免费的
                $surplus_time = $userInfo['overplus_time'];
            }else{
                $surplus_time = $userInfo['overplus_time']-$consume_time;
            }
        }else{
            if ($websiteInfo['fees'] ==1) //如果终端所在网点是免费的
            {
                $surplusTime = $chargingUserInfo['overplus_time'];
            }else {
                $surplusTime = $chargingUserInfo['overplus_time']-$consumeTime;
            }
        }
                        /*       $data['content']=2;
                                M('TestLog')->add($data);*/
        //免费权限
        $userAuth=$this->isAuth($userId);
        if($userAuth['auth_controller']==2) {
            $surplusTime = $chargingUserInfo['overplus_time'];
        }
        
        $array = array(
                'charging_log_id' => $chargingLogId,
                'end_time' => $endTime,                     //充电结束时间
                'status' => 1,                              //成功
                'consume_time' => $consumeTime,             //充值增加、充电消耗时间
                'surplus_time' => $surplusTime,           //剩余时间
        );

        $logInfo = $mLog->getByPk($chargingLogId);//重新查询一次是否已经被结束

        if($logInfo['status'] == 0){
            $mUser = D('Base/ChargingUser');
            $returnLog = $mLog->update($array);//结束更新表
            if($returnLog){
                $where = array(
                        'id' => $chargingUserInfo['id'],
                        'overplus_time' => $array['surplus_time'],
                );
                $returnUser = $mUser->update($where);//更新用户表

                $returnScheduled = $this->insertCode($websiteInfo,$terminalInfo,$userId,$chargingId,2);
                if(!$returnScheduled){
                    $this->ajaxReturn(array('status'=>'F','message'=>'拉闸失败'));
                }else{
	                if($this->isAlipayBrower()){
		                $account = M("Charging")->where(array('charging_id'=>$chargingId))->field('account_id')->limit(1)->find();
		                $alipay  = M("Alipay")->where(array('account_id'=>$account['account_id']))->field('alipay_id')->limit(1)->find();
		                $aluser  = M("AlipayUser")->where(array('user_id'=>$userId))->field('alipay_user_id')->limit(1)->find();
		                $stat_time = date("Y-m-d H:i:s",$logInfo['start_time']);
		                $end_time  = date("Y-m-d H:i:s");
		                $message = array(
			                'head_color'=>'#85be53',
			                'url'=>C('site_url').'/base/NewCharging/index/chargingId/'.$chargingId,
			                'action_name'=>'详情',
			                'keyword1'=>array('color'=>'#000000','value'=>'您的小毛驴已经充电完成啦'),
			                'keyword2'=>array('color'=>'#000000','value'=> $stat_time),
			                'keyword3'=>array('color'=>'#000000','value'=>$logInfo['freezing_time'].'分钟'),
			                'keyword4'=>array('color'=>'#000000','value'=>$end_time),
			                'first'   =>array('color'=>'#bebebe','value'=>date("m月d日")),
			                'remark'  =>array('color'=>'#FF0000','value'=>'小毛驴已充电完成，主人，请尽快带它离开，以免耽误他人充电哦！')
		                );
		                $AlipayService = service('Alipay');
		                $AlipayService->sendMessage($alipay['alipay_id'],$aluser['alipay_user_id'],$message,"2ae8e3e6b8ec461c8562a676b92c9635");
	                }else {
		                $mWechatUser = D('Wechat/WechatUser');
		                $WechatUserInfo = $mWechatUser->getByUserId($userId);
		                if ($logInfo['charging_id'] != 12) {
			                if ($WechatUserInfo['subscribe']) {
				                //给用户推消息
				                import("@.Msgtpl.Base.ChargingMsgtpl");
				                $chargingMsgtpl = new ChargingMsgtpl($WechatUserInfo['wechat_id']);
				                $chargingMsgtpl->sendMessageToUser2($WechatUserInfo, $logInfo, $chargingId);
			                }
		                }/*else{
                        import('ORG.Crypt');
                        $appid = 'api1465347484';
                        $key = 'd3e23167f55f0804c4d36e2058ddd3b3';
                        $secret = Crypt::encrypt($appid,$key);
                        $url = 'http://wx.app.nbpt.edu.cn/weixin/api/electricity_notify';
                        $data = array(
                            'secret'=>base64_encode($secret),
                            'accountId'=>13,
                            'tId'=>$logInfo['terminal_id'],
                            'openid'=>$WechatUserInfo['openid'],
                            'cId'=>$logInfo['charging_log_id'],
                            'remainTime'=>$surplusTime,
                            'exceptTime'=>$endTime
                        );
                        import('ORG.Http');
                        $header = array(
                        );
                        //error_log('resultcc-'.var_export($data,true),3,'/tmp/wxl.log');
                        $result = Http::curlPost($url,$data,$header);
                       // error_log('resultbb-'.$result,3,'/tmp/wxl.log');
                    }*/
	                }
                }
                return array('status'=>'S','message'=>'操作成功');
            }
        }else{
            return array('status'=>'S','message'=>'已操作成功');
        }

    }

     //插入拉闸的指令  type:1合闸，2：拉闸  value:时间
    public function insertCode($websiteInfo,$terminalInfo,$userId,$chargingId,$type = 1,$value=0){
            
            //获得指令
            $meterArr = $this->checkMeterType($value,$terminalInfo,$type);

            $mCharging = D('Base/Charging');
            $chargingInfo = $mCharging->getInfo(array('charging_id'=>$chargingId));

            $condition = array(
                        'website_id' => $websiteInfo['website_id'],
                        'terminal_id' => $terminalInfo['terminal_id'],
                        'terminal_code' => $terminalInfo['terminal_code'],
                        'operate_code' => $meterArr['supply_operate_code'],
                        'ip' => $websiteInfo['hub_socket_ip'],
                        'port' => $websiteInfo['hub_socket_port'],
                        'type' => $type,
                        'address_id' => $websiteInfo['hub_device_id'],
                        'out_success' => $meterArr['out_success'],
                        'notify_url' => C('site_url').U('Base/ChargingUpdate/index'),
                        'create_time' => time(),
                        'user_id' => $userId,
                        'account_id' => $chargingInfo['account_id'],
            );
                $mScheduled = D('Base/ChargingScheduledTasks');
                $returnScheduled = $mScheduled->update($condition);//更新任务表
                
               return $returnScheduled;
    }


    /*检测充电状态*/
    public function checkCharge($chargingLogId){
        $mLog = D('Base/ChargingLog');
        $logInfo = $mLog->getByPk($chargingLogId , 'status,charging_log_id');
        if($logInfo !== false && $logInfo['status'] == 1){
            return array('status'=>'S','message'=>'充电已结束');
        }else{
            return array('status'=>'F','message'=>'正在充电中');
        }
    }



    /*定时任务(暂时还是使用chargingAction中的)*/
    public function timedTask(){
        set_time_limit(0);
        $mWechatUser = D('Wechat/WechatUser');
        $mCharing = D('Base/Charging');
        $mLog = D('Base/ChargingLog');
        $mWebsite = D('Base/ChargingWebsite');
        $mTerminal = D('Base/ChargingTerminal');
        $mScheduled = D('Base/ChargingScheduledTasks');
        $mUser = D('Base/ChargingUser');
        
        $condition = array(
                'status'=>0,
                'type' => 1
        );
        $field = 'charging_log_id,charging_id,website_id,user_id,terminal_id,start_time,freezing_time';
        $logList = $mLog->getList($condition,$field,'charging_log_id');//正在充电记录的列表
        
        foreach ($logList as $key => $value){
            
            $accountId = $mCharing->getFieldByCharingId($value['charging_id'],'account_id');//获取账号
            $condition = array(
                    'user_id' => $value['user_id'],
                    'charging_id' => $value['charging_id'],
            );
            $userInfo = $mUser->getInfo($condition , 'user_id,id,overplus_time');//用户信息
            
            if(!$userInfo){
                break;
            }
            $terminalInfo = $mTerminal->getByPk($value['terminal_id']);//终端信息
            $websiteInfo = $mWebsite->getByPk($value['website_id']);//网点信息
            
            $end_time = time();
            $consume_time = ceil(($end_time - $value['start_time'])/60);
            
            
            if($value['charging_id']== 12){
                $mUsers = D('User');
                $uInfo = $mUsers->getByUserId($value['user_id']);
                if($uInfo['type'] == 1){//宁职院 教师是免费的
                    $surplus_time = $userInfo['overplus_time'];
                }else{
                    $surplus_time = $userInfo['overplus_time']-$consume_time;
                }
            }else{
                if ($websiteInfo['fees'] ==1) //如果终端所在网点是免费的
                {
                    $surplus_time = $userInfo['overplus_time'];
                }else {
                    $surplus_time = $userInfo['overplus_time']-$consume_time;
                }
            }
            
            if($consume_time >= $value['freezing_time']){//如果充电时间超出冻结时长则改为冻结时长并结束任务
                $consume_time = $value['freezing_time'];
                $array = array(
                        'charging_log_id' => $value['charging_log_id'],
                        'end_time' => $end_time,
                        'status' => 1,
                        'consume_time' => $consume_time,
                        'surplus_time' => $surplus_time,//$userInfo['overplus_time']-$consume_time,
                            
                );
                $logInfo = $mLog->getByPk($value['charging_log_id'],'status');//重新查询一次是否已经被结束
                
                if($logInfo['status'] == 0){
                    $returnLog = $mLog->update($array);//结束更新表
                    if($returnLog){
                        $where = array(
                                'id' => $userInfo['id'],
                                'overplus_time' => $array['surplus_time'],
                        );
                        $returnUser = $mUser->update($where);//更新用户表
                

                        $returnScheduled = $this->insertCode($websiteInfo,$terminalInfo,$value['user_id'],$value['charging_id'],2);

                        if(!$returnScheduled){
                            break;
                        }else{
                             if($this->isAlipayBrower()){
                                $account = M("Charging")->where(array('charging_id'=>$value['charging_id']))->field('account_id')->limit(1)->find();
                                $alipay  = M("Alipay")->where(array('account_id'=>$account['account_id']))->field('alipay_id')->limit(1)->find();
                                $aluser  = M("AlipayUser")->where(array('user_id'=>$value['user_id']))->field('alipay_user_id')->limit(1)->find();
                            
                                $stat_time = date("Y-m-d H:i:s",$logInfo['start_time']);
                                $end_time  = date("Y-m-d H:i:s",($logInfo['end_time']));
                                $message = array(
                                    'head_color'=>'#85be53',
                                    'url'=>C('site_url').'/base/NewCharging/index/chargingId/'.$value['charging_id'],
                                    'action_name'=>'详情',
                                    'keyword1'=>array('color'=>'#000000','value'=>'您的小毛驴已经充电完成啦'),
                                    'keyword2'=>array('color'=>'#000000','value'=> $stat_time),
                                    'keyword3'=>array('color'=>'#000000','value'=>$log['freezing_time'].'分钟'),
                                    'keyword4'=>array('color'=>'#000000','value'=>$end_time),
                                    'first'   =>array('color'=>'#bebebe','value'=>date("m月d日")),
                                    'remark'  =>array('color'=>'#FF0000','value'=>'小毛驴已充电完成，主人，请尽快带它离开，以免耽误他人充电哦！')
                                );
                                $AlipayService = service('Alipay');
                                $AlipayService->sendMessage($alipay['alipay_id'],$aluser['alipay_user_id'],$message,"2ae8e3e6b8ec461c8562a676b92c9635");
                            }else {
                                $WechatUserInfo = $mWechatUser->getByUserId($value['user_id']);
                                if($WechatUserInfo['subscribe']){                           

                                    //模板空间
                                    //给用户推消息
                                    import("@.Msgtpl.Base.ChargingMsgtpl");
                                    $chargingMsgtpl = new ChargingMsgtpl($WechatUserInfo['wechat_id']);
                                    $chargingMsgtpl->sendMessageToUser2($WechatUserInfo,$logInfo,$value['charging_id']);
                                }
                            }
                        }
                    }
                }
            }
            
        }
    }

    //检测电流(针对Golive表)
    public function checkPower($websiteId,$terminalId){
        $mTerminal = D('Base/ChargingTerminal');
        $condition = array(
            'cur_off'   =>  0,
            'meter_type'=>  'Golive'
            );
        $list = $mTerminal->getList($condition);
        $terminalIds = array();
        foreach($list as $v){
            $terminalIds[] = $v['terminal_id'];
        }

        $mLog = D('Base/ChargingLog');

        if($terminalIds){
            $cCondition = array(
                'status'    =>  0,
                'terminal_id'=> array('in',$terminalIds)
                );
            $logList = $mLog->getList($cCondition);
            foreach($logList as $vv){
                $websiteInfo = $this->getWebsite($vv['website_id']);
                $terminalInfo = $this->getTerminal($vv['terminal_id']);
                //插入检测电流指令
                $this->insertCode($websiteInfo,$terminalInfo,0,$websiteInfo['charging_id'],3,0);
            }
        }
    }

	/**
	 * 判断是否是支付宝浏览器
	 * @return boolean
	 */
	public function isAlipayBrower(){
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') != false){
			return true;
		}else{
			return false;
		}
	}
    /**
     * 判断是否有权限
     * @return array
     */
    public function isAuth($userId)
    {
        $charginguserModel = D('ChargingUser');
        $auth = $charginguserModel->alias('a')->join("gc_charging_auth b on a.user_id=b.user_id")->where(array('a.user_id' => $userId))->field('b.auth_controller')->find();
        return $auth;
    }

}